package com.xigua._树;

import com.xigua.TreeNode;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: 你需要采用前序遍历的方式，将一个二叉树转换成一个由括号和整数组成的字符串。
 * 空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
 *
 * @date 2022/3/1911:35
 */
public class _606_根据二叉树创建字符串 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode left = new TreeNode(2,null,new TreeNode(4));
        TreeNode right = new TreeNode(3);
        root.right = right;
        root.left = left;
        System.out.println(tree2str(root));
    }

    public static String tree2str(TreeNode root) {
        StringBuffer stringBuffer = new StringBuffer();
        helper(root,stringBuffer);
        return stringBuffer.toString();
    }

    public static void helper(TreeNode root,StringBuffer stringBuffer){
        if (root!=null && stringBuffer.toString().equals("")){
            stringBuffer.append(root.val);
            if (root.left == null && root.right != null) {
                stringBuffer.append("()");
                helper(root.right,stringBuffer);
            }else{
                helper(root.left,stringBuffer);
                helper(root.right,stringBuffer);
            }


            return;
        }
        if (root == null) return;
        if (root.right != null && root.left!=null){
            stringBuffer.append("("+root.val);
            helper(root.left,stringBuffer);
            helper(root.right,stringBuffer);
            stringBuffer.append(")");
        }else if (root.left != null && root.right ==null){
            stringBuffer.append("("+root.val);
            helper(root.left,stringBuffer);
            stringBuffer.append(")");
        }else if (root.left == null && root.right !=null) {
            stringBuffer.append("("+root.val);
            stringBuffer.append("()");
            helper(root.right, stringBuffer);
            stringBuffer.append(")");
        }else if (root.left == null && root.right ==null){
            stringBuffer.append("("+root.val+")");
        }
    }

}
